import  os
import  string

g_config = {}
g_counts = {}

def initConfig():

    #    let the sub know that it is operating on the global.  very odd arrangement!

    global  g_config

    config_path = 'c:\\teach-perl\\process-files\config.txt'

    if  ( os.path.exists( config_path ) ):

        #    process the file.
        for line in open( config_path, 'r' ):

            parts = line.split( '=' )

            #    remove the EOL at the end of the value via the [:-1]
            g_config[parts[0]] = parts[1][:-1]

    else:
        print   'Unable to find the config_path at ' + config_path
        sys.exit( 0 )

#        

def getConfigVal( key ):

        #    return the value for the given config key.

        retval = ''

        #    load up the global config if not already loaded.
        if  len( g_config ) == 0:

            initConfig()

        # attempt to get the entry
        try:
            retval = g_config[key]
        except:
            print( 'Encountered unexpected key= ' + key )
        finally:
                print   "key=" + retval

        return retval
#

def workThruFiles( input_dir ):

    words = {}

    global  g_counts

    for file in os.listdir( input_dir ):

        path = os.path.join( input_dir, file )

        if  os.path.isfile( path ):

            print   'Processing file ' + path

            for line in open( path, 'r' ):

                line = line[:-1]

                #    remove extra spaces

                line = line.replace( '  ', '' )

                words_on_line = line.split( ' ' )

                for word in words_on_line:

                    try:
                        g_counts[word] = g_counts[word] + 1
                        print   'Setting count to ' + str( g_counts[word] ) + ' for ' + word
                    except:
                        g_counts[word] = 1
                        print   'Initializing to ' + str( g_counts[word] ) + ' for ' + word
#

def dumpStats():

    #    dump the word counts in sorted order.

    global  g_counts

    items = g_counts.items()

    items.sort()

    for x in items:

        print   str( x[0] ) + '=' + str( x[1] )


def countWords():

    print   ( 'Starting' )

    input_dir = getConfigVal( 'INPUT_DIR' )

    print   'INPUT_DIR=' + input_dir

    print   ( 'Processing files' )
    workThruFiles( input_dir );

    print   ( 'Dumping Stats' )
    dumpStats()

#
#    Main
#

print   ( 'Starting main' )

countWords()

print   ( 'Ending main' )


